let $db := doc("xp")
return 
	(: Pour toutes les expériences :)
	insert node 
		<resultsByXp>
			{
			for $xp in $db/ranking/xps//xp
			let $sysNotation := $xp//req
			return 
			(: Pour tout les utilisateurs sans redoublon :)
				let $users := distinct-values(db:open(string($xp/@id), "historyResults.xml")/historyResults//user/@id)
				return 
				(: insertion des éléments :)
					<xp>
						{$xp/@id}
						{
						for $user in $users
						return 
							<user>
								<name>{$user}</name>
								{	
								for $notation in $sysNotation
								return
									(:Ouverture de la base qui contiens l'historique d'une xp et calcule des notes:)
									let $sum := fn:sum(db:open(string($xp/@id), "historyResults.xml")/historyResults//user[@id = $user]/notation[nom = $notation/nom/text()]/points)
									return
									<notation>
										<nom>{$notation/nom/text()}</nom>
										<points>{$sum}</points>
										<badges>
										{
											for $badge in $notation/badges//badge
											return 
												if ($sum >= $badge/note/text())
												then 
													<badge>
														<nom>{$badge/nom/text()}</nom>
													</badge>
												else ()			
										}
										</badges>
									</notation>	
								}
							</user>
						}
						</xp>
					}
				</resultsByXp>
				into $db/ranking/globalResults
				